﻿namespace Atomic.Mvc.Themes
{
    using System;
    using System.Collections.Generic;

    using Atomic.Mvc.Settings;

    /// <summary>
    /// 默认部件管理器。
    /// </summary>
    public class DefaultPartManager : IPartManager
    {
        /// <summary>
        /// 部件字典集合。
        /// </summary>
        private readonly IDictionary<string, IPart> _parts = new Dictionary<string, IPart>();

        /// <summary>
        /// 获得部件。
        /// </summary>
        /// <param name="id">部件唯一标识。</param>
        /// <returns>部件位置。</returns>
        public string Get(string id)
        {
            if (this._parts.ContainsKey(id))
            {
                return this.GetFullPath(this._parts[id]);
            }

            return string.Empty;
        }

        /// <summary>
        /// 增加部件。
        /// </summary>
        /// <param name="part">部件对象。</param>
        public void Add(IPart part)
        {
            if (part == null)
            {
                throw new ArgumentNullException("part", "part 对象不可以是空的。");
            }

            if (!this._parts.ContainsKey(part.Id))
            {
                this._parts[part.Id] = part;
            }
        }

        /// <summary>
        /// 获得完整虚拟路径。
        /// </summary>
        /// <param name="part">部件对象。</param>
        /// <returns>完整虚拟路径。</returns>
        protected virtual string GetFullPath(IPart part)
        {
            if (part.VirtualPath.Contains("\\"))
            {
                throw new ArgumentException("part.VirtualPath 字符串存在不合法字符。");
            }

            if (part.VirtualPath.StartsWith("~/"))
            {
                return string.Format("~/{1}/{0}/{2}", part.PluginId, part.PluginFolder, part.VirtualPath.Substring(2));
            }

            if (part.VirtualPath.StartsWith("/"))
            {
                return string.Format("~/{1}/{0}/{2}", part.PluginId, part.PluginFolder, part.VirtualPath.Substring(1));
            }

            return string.Empty;
        }
    }
}